<template>
  <div v-if="moduleNameOptions && activePageForm">
    <el-dialog
      :title="
        (mode === 'add' ? '新增' : '编辑') +
          moduleNameOptions[
            activePageForm.modules[activePageForm.activeModuleIndex].type
          ].label
      "
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      :append-to-body="true"
      width="850px"
      @close="close"
    >
      <el-form
        ref="form"
        v-loading="false"
        :model="form"
        :rules="rules"
        label-width="110px"
        size="small"
      >
        <el-form-item label="一级分类标题" prop="menuName">
          <el-input
            v-model.trim="form.menuName"
            maxlength="4"
            show-word-limit
            class="w-200"
          />
          <el-checkbox
            v-model="isTwoClassify"
            style="margin-left: 10px"
            @change="checkboxChange"
          >是否启用二级分类</el-checkbox>
          <el-button
            v-if="isTwoClassify"
            icon="el-icon-plus"
            size="small"
            round
            type="text"
            @click="form.goodsMenuForms.push({ menuName: null,type: 0, goodsList: [], categoryList: [] })"
          >增加二级分类</el-button>
        </el-form-item>
        <!-- 只有一级标题 -->
        <div v-if="!isTwoClassify">
          <el-form-item label="商品：" prop="ranking" class="is-required">
            <div>
              <el-select v-model="form.type" placeholder="请选择">
                <el-option :value="0" label="手工上架商品" />
                <el-option :value="1" label="自动从类别中获取" />
              </el-select>
              <el-button
                v-if="form.type == 1"
                icon="el-icon-plus"
                size="small"
                round
                type="text"
                @click="addCategory"
              >
                选择类目
              </el-button>
              <el-button
                v-if="form.type == 0"
                icon="el-icon-plus"
                size="small"
                round
                type="text"
                @click="addGoods"
              >增加商品
              </el-button>
            </div>
          </el-form-item>

          <el-form-item :prop="typePropOptions[form.type]" class="is-required">
            <el-table
              v-if="form.type == 0"
              :data="form.goodsList"
              style="width: 100%"
              empty-text="未选择商品"
              border
              stripe
              class="goods-container"
              size="small"
              max-height="500"
            >
              <el-table-column prop="coverImg" label="图片" width="50">
                <template slot-scope="scope">
                  <img
                    :src="fileBaseUrl + scope.row.coverImg"
                    alt
                    class="cover-img"
                  >
                </template>
              </el-table-column>
              <el-table-column prop="title" label="商品" />
              <el-table-column prop="category" label="类别">
                <template slot-scope="scope">{{
                  scope.row.category.join(' > ') || '-'
                }}</template>
              </el-table-column>
              <el-table-column label="操作" width="80">
                <template slot-scope="scope">
                  <el-button
                    size="small"
                    round
                    type="text"
                    class="app-text-color-danger"
                    @click="delGoods(form.goodsList, scope.$index)"
                  >删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-table
              v-if="form.type == 1"
              :data="form.categoryList"
              style="width: 100%"
              empty-text="未选择类目"
              border
              stripe
              class="category-container"
              size="small"
              max-height="500"
            >
              <el-table-column prop="name" label="类别">
                <template slot-scope="scope">{{
                  scope.row.names.join(' > ') || '-'
                }}</template>
              </el-table-column>
              <el-table-column label="操作" width="80">
                <template slot-scope="scope">
                  <el-button
                    size="small"
                    round
                    type="text"
                    class="app-text-color-danger"
                    @click="delCategory(form.categoryList, scope.$index)"
                  >删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </div>
        <!-- 有二级分类 -->
        <div v-if="isTwoClassify">
          <el-form
            v-for="(item, index) in form.goodsMenuForms"
            :key="index"
            ref="form1"
            v-loading="false"
            :model="item"
            :rules="rules2"
            label-width="110px"
            size="small"
          >
            <el-form-item label="二级分类标题" prop="menuName">
              <el-input

                v-model.trim="item.menuName"
                maxlength="4"
                show-word-limit
                class="w-200"
              />
              <el-button
                size="small"
                style="color: red"
                round
                type="text"
                @click="form.goodsMenuForms.splice(index, 1)"
              >删除二级分类</el-button>
            </el-form-item>

            <el-form-item label="商品：" prop="ranking" class="is-required">
              <div>
                <el-select v-model="item.type" placeholder="请选择" @change="selectChange(item)">
                  <el-option :value="0" label="手工上架商品" />
                  <el-option :value="1" label="自动从类别中获取" />
                </el-select>
                <el-button
                  v-if="item.type == 1"
                  icon="el-icon-plus"
                  size="small"
                  round
                  type="text"
                  @click="addCategory(index)"
                >
                  选择类目
                </el-button>
                <el-button
                  v-if="item.type == 0"
                  icon="el-icon-plus"
                  size="small"
                  round
                  type="text"
                  @click="addGoods(index)"
                >增加商品
                </el-button>
              </div>
            </el-form-item>

            <el-form-item
              :prop="typePropOptions[item.type]"
              class="is-required"
            >
              <el-table
                v-if="item.type == 0"
                :data="form.goodsMenuForms[index].goodsList"
                style="width: 100%"
                empty-text="未选择商品"
                border
                stripe
                class="goods-container"
                size="small"
                max-height="500"
              >
                <el-table-column prop="coverImg" label="图片" width="50">
                  <template slot-scope="scope">
                    <img
                      :src="fileBaseUrl + scope.row.coverImg"
                      alt
                      class="cover-img"
                    >
                  </template>
                </el-table-column>
                <el-table-column prop="title" label="商品" />
                <el-table-column prop="category" label="类别">
                  <template slot-scope="scope">{{
                    scope.row.category.join(' > ') || '-'
                  }}</template>
                </el-table-column>
                <el-table-column label="操作" width="80">
                  <template slot-scope="scope">
                    <el-button
                      size="small"
                      round
                      type="text"
                      class="app-text-color-danger"
                      @click="delGoods(item.goodsList, scope.$index)"
                    >删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
              <el-table
                v-if="item.type == 1"
                :data="item.categoryList"
                style="width: 100%"
                empty-text="未选择类目"
                border
                stripe
                class="category-container"
                size="small"
                max-height="500"
              >
                <el-table-column prop="name" label="类别">
                  <template slot-scope="scope">{{
                    scope.row.names.join(' > ') || '-'
                  }}</template>
                </el-table-column>
                <el-table-column label="操作" width="80">
                  <template slot-scope="scope">
                    <el-button
                      size="small"
                      round
                      type="text"
                      class="app-text-color-danger"
                      @click="delCategory(item.categoryList, scope.$index)"
                    >删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
          </el-form>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          :disabled="loading"
          size="small"
          round
          @click="hide"
        >取 消</el-button>
        <el-button
          :disabled="loading"
          size="small"
          round
          type="primary"
          @click="submit"
        >确 定</el-button>
      </div>
    </el-dialog>
    <!-- 组件 -->
    <DialogGoods ref="dialogGoods" />
    <DialogCategory ref="dialogCategory" />
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { imgUploadUrl } from '@/api/upload'
import { saveMenu } from '@/views/wxaBuildModule/api/store'
import DialogGoods from './DialogGoods'
import DialogCategory from './DialogCategory'
import wxaBuildConfig from '@/views/wxaBuildModule/config'

export default {
  components: {
    DialogGoods,
    DialogCategory
  },
  data() {
    return {
      // 校验字段
      rules: {
        menuName: [
          {
            required: true,
            message: '请输入一级标题',
            trigger: ['blur', 'change']
          }
        ],
        categoryList: [
          {
            type: 'array',
            required: true,
            message: '请选择类目',
            trigger: ['blur', 'change']
          }
        ],
        goodsList: [
          {
            type: 'array',
            required: true,
            message: '请选择商品',
            trigger: ['blur', 'change']
          }
        ]
      },
      rules2: {
        menuName: [
          {
            required: true,
            message: '请输入二级标题',
            trigger: ['blur', 'change']
          }
        ],
        categoryList: [
          {
            type: 'array',
            required: true,
            message: '请选择类目',
            trigger: ['blur', 'change']
          }
        ],
        goodsList: [
          {
            type: 'array',
            required: true,
            message: '请选择商品',
            trigger: ['blur', 'change']
          }
        ]
      },
      // 配置
      resolve: null,
      reject: null,
      typePropOptions: {
        0: 'goodsList',
        1: 'categoryList'
      },
      imageUploadUrl: imgUploadUrl,
      moduleNameOptions: null,
      // 状态
      dialogVisible: null,
      loading: false,
      // 数据
      classifyCode: 'DEFAULT',
      mode: 'add',
      // 是否启用二级标题
      isTwoClassify: false,
      form: {
        menuName: null,
        type: 0,
        goodsList: [],
        categoryList: [],
        goodsMenuForms: [

        ]
      }
    }
  },
  computed: {
    ...mapGetters(['fileBaseUrl', 'activePageForm'])
  },
  watch: {
    'form.type'() {
      this.$nextTick((res) => {
        this.$refs.form.clearValidate(['categoryList', 'goodsList'])
      })
    }
  },
  methods: {
    selectChange(data) {
      data.type == 0 ? data.categoryList = [] : data.goodsList = []
    },
    /**
     * 弹框相关
     */
    checkboxChange(val) {
      if (val) {
        this.form.type = 2
        this.form.goodsMenuForms = [{ menuName: null, type: 0, goodsList: [], categoryList: [] }]
      } else {
        this.form.type = 0
        this.form.goodsMenuForms = []
        this.form.goodsList = []
        this.form.categoryList = []
      }
    },
    open({ mode = 'add', row = null }) {
      this.moduleNameOptions = wxaBuildConfig[this.classifyCode].moduleName
      this.mode = mode
      this.show()
      if (mode === 'edit' && row) {
        if (!row.goodsList) row.goodsList = []
        if (!row.categoryList) row.categoryList = []
        this.form = JSON.parse(JSON.stringify(row))
        this.form.type == 2 ? this.isTwoClassify = true : false
      }
      console.log(mode, row, this.form)

      return new Promise((resolve, reject) => {
        this.resolve = resolve
        this.reject = reject
      })
    },

    show() {
      this.dialogVisible = true
    },

    close() {
      this.loading = false
      this.form = {
        menuName: null,
        // 是否启用二级标题
        type: 0,
        goodsList: [],
        categoryList: [],
        goodsMenuForms: [
        ]
      }
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
      })

      console.log(this.form)
    },

    hide() {
      this.resolve = null
      this.reject = null
      this.dialogVisible = false
    },

    /**
     * 数据组
     */

    /**
     * 按钮组
     */
    // 确 定
    async submit() {
      if (this.form.type != 2) {
        this.$refs.form.validate((valid) => {
          if (valid) {
            this.loading = true
            const params = JSON.parse(JSON.stringify(this.form))
            if (params.type == 0) {
              params.categoryList = []
            } else if (params.type == 1) {
              params.goodsList = []
            } else if (params.type == 2) {
              params.categoryList = []
              params.goodsList = []
            }

            saveMenu(params)
              .then(res => {
                params.menuId = res.data
                this.resolve && this.resolve(params)
                this.isTwoClassify = false
                this.hide()
              })
          }
        })
      } else {
        this.$refs.form.validate((valid) => {
          if (valid) {
            console.log(this.$refs)
            let formValid = true
            for (let i = 0; i < this.$refs.form1.length; i++) {
              this.$refs.form1[i].validate(valid => {
                if (valid) {
                  if (i === this.$refs.form1.length - 1 && formValid) {
                    this.loading = true
                    const params = JSON.parse(JSON.stringify(this.form))
                    if (params.type == 0) {
                      params.categoryList = []
                    } else if (params.type == 1) {
                      params.goodsList = []
                    } else if (params.type == 2) {
                      params.categoryList = []
                      params.goodsList = []
                    }

                    saveMenu(params)
                      .then(res => {
                        params.menuId = res.data
                        this.resolve && this.resolve(params)
                        this.isTwoClassify = false
                        this.hide()
                      })
                  }
                } else {
                  formValid = false
                }
              })
            }
          }
        })
      }
      this.$store.dispatch('setActivePageForm', JSON.parse(JSON.stringify(this.activePageForm)))
    },

    // 新增类目
    addCategory(index) {
      const categoryIds = []
      if (this.isTwoClassify) {
        this.form.goodsMenuForms[index].goodsList = []
        this.form.goodsMenuForms[index].categoryList.forEach((v) => {
          categoryIds.push(v.id)
        })
        this.$refs.dialogCategory.open({ categoryIds }).then((res) => {
          this.form.goodsMenuForms[index].categoryList = res
          this.$refs.form.clearValidate(['categoryList'])
        })
      } else {
        this.form.categoryList.forEach((v) => {
          categoryIds.push(v.id)
        })
        this.$refs.dialogCategory.open({ categoryIds }).then((res) => {
          this.form.categoryList = res
          this.$refs.form.clearValidate(['categoryList'])
        })
      }
    },

    // 删除类目
    delCategory(data, index) {
      data.splice(index, 1)
    },

    // 新增商品
    addGoods(index) {
      const hasCheckedIds = []

      if (this.isTwoClassify) {
        this.form.goodsMenuForms[index].categoryList = []
        this.form.goodsMenuForms[index].goodsList.forEach((v) => {
          hasCheckedIds.push(v.goodsId)
        })

        this.$refs.dialogGoods.open({ hasCheckedIds }).then((res) => {
          this.form.goodsMenuForms[index].goodsList = this.form.goodsMenuForms[index].goodsList.concat(res)
          this.$refs.form.clearValidate(['goodsList'])
        })
        this.$forceUpdate()
      } else {
        this.form.goodsList.forEach((v) => {
          hasCheckedIds.push(v.goodsId)
        })
        this.$refs.dialogGoods.open({ hasCheckedIds }).then((res) => {
          this.form.goodsList = this.form.goodsList.concat(res)
          this.$refs.form.clearValidate(['goodsList'])
        })
      }
    },

    // 删除商品
    delGoods(data, index) {
      data.splice(index, 1)
    }

    /**
     * 状态组
     */

    /**
     * 方法组
     */
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.w-200 {
  width: 200px;
}

.w-400 {
  width: 400px;
}

/* 列表 */
.category-container {
  margin-top: 10px;

  .cell-item {
    display: flex;
  }
}

.goods-container {
  margin-top: 10px;

  .cover-img {
    width: 40px;
    height: 40px;
  }
}

/* 上传图片 */
.upload-container {
  display: flex;

  .el-icon-plus {
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 36px;
    color: #8c939d;
  }

  .img {
    display: block;
  }
}
</style>
